package com.xc.taoku.service.impl;

import com.xc.taoku.entity.Orderitem;
import com.xc.taoku.entity.Orders;
import com.xc.taoku.entity.Product;
import com.xc.taoku.entity.User;
import com.xc.taoku.mapper.OrderItemMapper;
import com.xc.taoku.mapper.OrderMapper;
import com.xc.taoku.service.IOrderService;
import com.xc.taoku.utils.NoUtils;
import com.xc.taoku.vo.CartVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    OrderItemMapper orderItemMapper;

    @Override
    public Orders saveOrder(List<CartVo> cartProduct, User user) {
        //产生订单信息
        Orders  orders = new Orders();
        //自动生成订单编号：
        String orderNo = NoUtils.getOrderNo();
        orders.setOid(orderNo);
        orders.setOrdertime(new Date());
        orders.setUid(user.getUid());
        orders.setState(1);
        double total = 0;
        //产生订单详情信息
        for (CartVo vo : cartProduct) {
            Orderitem oi = new Orderitem();
            oi.setItemid(UUID.randomUUID().toString());
            oi.setCount(vo.getCount());
            oi.setOid(orderNo);
            oi.setPid(vo.getProduct().getPid());
            double stat = vo.getProduct().getShopPrice() * vo.getCount();
            oi.setSubtotal(stat);
            orderItemMapper.insert(oi);

            total+=stat;
        }

        //订单总价
        orders.setTotal(total);
        orderMapper.insert(orders);

        return orders;
    }
}
